<!-- 技能树详情 -->
<template>
  <div class="pageWrap pageDetail hp100" style="margin-top:0;background: #fff;">
    <!-- <div class="breakNav">
      <div class="addressIcon"></div>
      <span>当前位置:</span>
      <span style="cursor: pointer" @click="returnParent">{{ pageTitle }}</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">{{ routeParams.name }}</span>
    </div> -->
    <div class="contentWrap">
      <!-- <section style="padding:5px 16px" class="startLR">
                <div >
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />鼠标悬浮文字可以进行增加，修改，删除，配置，查看等操作</span></p>
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />非叶子节点才能进行添加操作，叶子节点才能配置，查看操作</span></p>
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />点击文字或原点可以展开或收缩该节点下所有子节点</span></p>
                    <p><span class="tip"> <Icon type="ios-information-circle-outline" />蓝色原点为岗位，绿色为技能，灰色为叶子节点</span></p>
                </div>
                <div>
                    <Button type="primary" :disabled="hasRoot" ghost class="md-add-jh" @click="showAddRoot">创建根节点</Button>
                </div>
            </section> -->
      <div class="treeWrap">
        <!-- editGroup -->
        <div id="oprateDiv" class="oprateDiv" v-show="false" @mouseleave="hideOperate">
          <Icon
            title="创建"
            size="18"
            @click.native="append($event, svgData)"
            type="ios-add-circle-outline"
            v-if="!svgData.data.isLeafNode"
          />
          <Icon
            title="绑定训练内容"
            size="18"
            @click.native="appendRelative($event, svgData)"
            type="ios-infinite-outline"
          />
          <Icon
            title="修改"
            size="18"
            @click.native="editTree($event, svgData)"
            type="ios-brush-outline"
          />
          <Poptip confirm class="delBox" title="确定要删除吗?" @on-ok="delItem(svgData)">
            <Icon title="删除" size="18" type="ios-trash-outline" />
          </Poptip>
        </div>
        <!-- <SkillTree id="showTree" operateId="oprateDiv" :data="treeData" 
                    @node-mouseleave="(data) => {handlerDataUpdate(data,'mouseleave')}" 
                    @node-mouseenter="(data) => {handlerDataUpdate(data,'mouseenter')}">
                </SkillTree> -->
        <SkillTree
          v-if="treeDetail.creator"
          :treeId="$route.query.id"
          :dictList="dictList"
          :show="true"
          :type="isSelfOprate(false) ? 'edit-prev' : 'edit'"
          :collect="treeDetail.collect"
          ref="canvasEditor"
          @node-hover="
            (data) => {
              handlerDataUpdate(data, 'mouseenter');
            }
          "
        ></SkillTree>
      </div>
    </div>
    <Modal
      v-model="oprateModal"
      :title="!editState ? '创建节点' : '修改节点'"
      @on-cancel="closeModal"
      @on-ok="dSubmitBtn"
      :mask-closable="false"
      :width="800"
      :loading="load"
      style="min-width:540px;width:auto"
    >
      <!-- :footer-hide="true" -->
      <!-- <div class="modal-header" v-if="svgData.data.name" >
                <Tooltip max-width="260" :content="svgData.data.name">
                    <h4 class="mgr15 font14 node-css">{{isRoot?'节点名称':'上层节点'}}：{{svgData.data.name}}</h4>
                </Tooltip>
                    <Tag color="blue" v-if="svgData.data.difficulty">{{mapDifficulty(svgData.data.difficulty)}}</Tag>
                    <Tag color="blue" v-if="svgData.data.type">{{mapType(svgData.data.type)}}</Tag>
                    <Tag color="blue" v-if="svgData.data.typeCode">{{mapTypeCode(svgData.data.typeCode)}}</Tag>
            </div> -->
      <div class="modal-content">
        <!-- <span v-if="!editState" class="addType">
                        <label for="addtype">创建方式</label>
                        <RadioGroup id="addtype" v-model="addType"  @on-change="changeAddType" >
                        <Radio :label="1">从已存在的技能树中添加</Radio>
                        <Radio :label="0">直接创建</Radio>  
                        </RadioGroup>
                </span> -->
        <Form
          ref="formValidate"
          :model="formValidate"
          :rules="ruleValidate"
          :label-width="100"
          class="primaryBgColor"
        >
          <span v-if="addType == 1">
            <!-- 从技能树中添加 -->
            <div class="startLR">
              <!-- <div class="whiteBgColor preLeft">
                            <Input suffix="ios-search" search v-model="queryObj.name" placeholder="输入技能树名称" @on-search="searchTree" style="width: auto" />
                            <ul class="treelist">
                            <li :class="list.name==activeName?'active':''" v-for="list in treeList" :key="list.id" @click="setSmallTreePre(list.id,list.name)" ><a>{{list.name}}</a></li>
                            </ul>
                            <Page class="mt16" :total="treeListTotal" show-total @on-change="pageChange" @on-page-size-change="sizeChange" />
                        </div> -->
              <div class="listItemTreePre whiteBgColor" @contextmenu="handlePaste($event)">
                <h4>
                  <!-- 预览区 -->
                  <p>
                    <span style="color:#f90;margin-right:16px;line-height: 35px;">
                      <Icon
                        type="ios-information-circle-outline"
                      />点击节点可以复制当前节点以及下面的所有子节点，点击确定按钮将当前复制的内容插入到当前打开的节点中</span
                    >
                  </p>
                  <!-- <p><span style="color:#f90;margin-right:16px;line-height: 35px;"> <Icon type="ios-information-circle-outline" />创建根节点的时候不能复制叶子节点</span></p> -->
                </h4>
                <div id="preTree">
                  <SkillTree
                    v-if="oprateModal"
                    :treeId="activeId"
                    :dictList="dictList"
                    type="check"
                    ref="canvasPrev"
                    @node-check="addDataFromTree"
                  ></SkillTree>
                </div>
              </div>
            </div>
          </span>
          <span v-if="addType == 0">
            <!-- 直接添加 -->
            <FormItem label="名称" prop="name" key="name">
              <Input v-model="formValidate.name" placeholder="请输入名称"></Input>
            </FormItem>
            <FormItem label="类型" prop="type" key="type">
              <RadioGroup v-model="formValidate.type">
                <Radio label="1">岗位</Radio>
                <Radio label="2">技能</Radio>
              </RadioGroup>
            </FormItem>
            <!-- :disabled="skillLearn&&editState" -->
            <FormItem label="等级" prop="difficulty" key="difficulty">
              <RadioGroup v-model="formValidate.difficulty">
                <Radio label="low">初级</Radio>
                <Radio label="middle">中级</Radio>
                <Radio label="high">高级</Radio>
              </RadioGroup>
            </FormItem>
            <!-- <FormItem label="叶子节点" prop="isLeafNode" key="isLeafNode">
                            <RadioGroup v-model="formValidate.isLeafNode">
                                <Radio :label="0" :disabled="isRoot||editState">否</Radio>
                                <Radio :label="1" :disabled="isRoot||editState">是</Radio>
                            </RadioGroup>
                        </FormItem> -->
            <FormItem label="图片" prop="image" v-if="formValidate.isLeafNode">
              <ItemUpload
                ref="imageUpload"
                :formatArr="['jpg', 'jpeg', 'png']"
                fileType="images"
                @upload-success="getUrl"
              ></ItemUpload>
              <div class="chose-wrap" v-show="formValidate.image">
                <div class="chose-name">
                  <img
                    :src="handleImage(formValidate.image)"
                    style="max-height: 30px;vertical-align: middle;"
                  />
                </div>
                <img
                  src="../../../assets/globalIcon/dis-del.png"
                  @click="formValidate.image = ''"
                />
              </div>
            </FormItem>
            <FormItem
              label="技能方向"
              prop="typeCode"
              v-if="formValidate.isLeafNode"
              key="typeCode"
            >
              <Select filterable
                v-model="formValidate.typeCode"
                placeholder="选择技能方向"
                multiple
                filterable
                :disabled="formValidate.points && Boolean(formValidate.points.length)"
              >
              <!--  @on-change="setDictTypeCode" -->
                <Option v-for="item in dictListDirection" :value="item.dictid" :key="item.dictid">{{
                  item.dictname
                }}</Option>
              </Select>
            </FormItem>
            <!-- <FormItem
              label="技能类型"
              prop="typeCode"
              v-if="formValidate.isLeafNode"
              key="typeCode"
            >
              <Select filterable
                v-model="formValidate.typeCode"
                :disabled="formValidate.points && Boolean(formValidate.points.length)"
                placeholder="选择技能类型"
              >
                <Option v-for="item in dictListTypeCode" :value="item.dictid" :key="item.dictid">{{
                  item.dictname
                }}</Option>
              </Select>
            </FormItem> -->
            <FormItem
              label="过关条件"
              prop="extension"
              v-if="formValidate.isLeafNode"
              key="extension"
            >
              <!-- <Input type="textarea" :autosize="{minRows: 2,maxRows: 5}" v-model="formValidate.extension" placeholder='请用JSON格式输入入过关条件，类似{"a":"bb"}'/> -->
              <div v-for="rule in ruleList" :key="rule.id" style="margin-bottom:12px">
                <template v-if="rule.show">
                  <Select filterable
                  :disabled="true"
                  v-model="rule.type"
                  placeholder="配置过关规则"
                  style="width: 160px"
                >
                  <!-- 类型：0.课程、1.课件、2.视频、3.考试、4.场景 -->
                  <Option :value="0">课程</Option>
                  <Option :value="1">课件</Option>
                  <Option :value="2">视频</Option>
                  <Option :value="3">考试</Option>
                  <Option :value="4">场景</Option>
                </Select>
                <Input
                  @on-blur="setExtensionInput(rule)"
                  :disabled="rule.type == 0 || rule.type == 1 || rule.type == 2"
                  v-model="rule.content"
                  placeholder="输入规则信息"
                  style="width: 200px"
                />
                <span
                  style="color:#f90;margin-right:16px;line-height: 35px;"
                  v-if="rule.type == 0 || rule.type == 1 || rule.type == 2"
                  >默认使用{{ mapTypeRule[rule.type] }}已学规则</span
                >
                <span style="color:#f90;margin-right:16px;line-height: 35px;" v-if="rule.type == 3"
                  >默认考试总分的60%为通过</span
                >
                <span style="color:#f90;margin-right:16px;line-height: 35px;" v-if="rule.type == 4"
                  >默认完成场景内50%以上的靶标题目或者任务</span
                >
                </template>
              </div>
            </FormItem>
          </span>
        </Form>
        <!-- <div class="oprateBtn">
                    <Button type="primary" @click="submitBtn('formValidate')" >确定</Button>
                </div> -->
      </div>
    </Modal>
    <skill-tree-plan ref="skillTreePlan" @close="updatePoints"></skill-tree-plan>
  </div>
</template>

<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import usally from '@/mixin/usally';
import { experType } from '@/api/dict';
import {
  querySkillChapter,
  delSkillChapter,
  addSkillChapter,
  modifySkillChapter,
  querySkill,
  nodeCopy,
  querySkillPoint,
  getSysConfig
} from '@/api/selfStudy/skill.js';
import skillTreePlan from './skillTreePlan.vue';
import { debounce, throttle } from '@/libs/utils';
import ItemUpload from '@/components/item-upload';
import SkillTree from './skillTree.vue';
import pageTitle from '@/mixin/pageTitle';
export default {
  name: 'chapters',
  components: { skillTreePlan, ItemUpload, SkillTree },
  props: [],
  mixins: [usally,pageTitle],
  data() {
    const validateJSON = (rule, value, callback) => {
      if (value) {
        try {
          let json = JSON.parse(value).extension;
          let flag = json.every((item) => item.content);
          if (flag) {
            const reg = /^[123456789]\d*$/;
            //  json[4].content 为场景 验证
            if (reg.test(json[3].content) ) { //&& reg.test(json[4].content)
              let v = json[3].content;
              // let s = json[4].content;
              v = v * 1;
              // s = s * 1;
              if (v > 0 && v <= 100) { //&& s > 0 && s <= 100
                callback();
              } else {
                callback(new Error('请输入0-100之间的数字'));
              }
            } else {
              callback(new Error('请输入大于0的数字'));
            }
          } else {
            callback(new Error('输入考试或场景规则'));
          }
        } catch (err) {
          callback(new Error('请输入json格式的字符串'));
        }
      } else {
        callback(new Error('请输入过关条件'));
      }
    };
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      passRuleType: 0,
      ruleId: 1,
      passRuleContent: '',
      load: true,
      addType: 0,
      isRoot: false,
      ruleListCopy: [
        { type: 0, content: '默认' ,show:this.course},
        { type: 1, content: '默认' ,show:this.showAllExperiment},
        { type: 2, content: '默认' ,show:this.videoLearn},
        { type: 3, content: '60' ,show:this.exam},
        // { type: 4, content: '50' }
      ],
      ruleList: [],
      queryObj: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
        id: this.$route.query.id
      },
      routeParams: {},
      currentCopy: {},
      hasRoot: true,
      divLeft: '0px',
      divLeftM: '0px',
      divTop: '0px',
      oprateModal: false,
      treeData: '', //详情页的
      preTreeData: '', //添加节点中显示的
      svgW: 0,
      svgH: 0,
      svgHs: 0,
      svgWs: 0,
      zIndex: -1,
      divScale: 1,
      searchName: '',
      editGroup: false,
      currentData: {},
      svgData: {
        data: {}
      },
      //tree
      editState: false,
      treeDataList: [],
      buttonProps: {
        type: 'default',
        size: 'small'
      },
      // 输入框要修改的内容
      inputContent: '',
      // 修改前的TreeNode名称
      oldName: '',
      showDefImg: true,
      showDefText: '加载中',
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      updateChapterArea: false,
      // 页面标题
      titleText: '权重配置',
      complete: false,
      parentItem: {},
      addItemObj: {},
      currentAddIndex: 0,
      addItemLenth: 0,
      activeName: '',
      activeId: '',
      endLevel: 1,
      addItems: [],
      dictList: [],
      dictListDirection: [],
      dictListTypeCode: [],
      skillLearn: false,
      // 方案id
      weightId: '',
      weightName: '',
      // 段落列表
      chapterData: [],
      originLinkData: [],
      currData: {},
      odlEditTreeChapter: {},
      currParentChapter: {},
      // 创建技能树
      level: 1,
      formValidate: {
        name: '',
        difficulty: 'low',
        typeCode: [],
        direction: '',
        isLeafNode: 0,
        type: '1',
        extension: JSON.stringify({ extension: this.ruleList }),
        image: ''
      },
      ruleValidate: {
        name: [
          { required: true, message: '请输入名称', trigger: 'change' },
          { type: 'string', max: 24, message: '名称最长为24个字符', trigger: 'change' }
        ],
        difficulty: [{ required: true, message: '请选择等级', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        isLeafNode: [
          {
            required: true,
            type: 'number',
            message: '请选择是否为叶子节点',
            trigger: 'change'
          }
        ],
        // typeCode: [{ required: true, type:'array',min:1,message: '请选择技能类型', trigger: 'change' }],
        // direction: [{ required: true, message: '请选择技能方向', trigger: 'change' }],
        extension: [
          { required: true, message: '请输入过关条件', trigger: 'change' },
          { validator: validateJSON, trigger: 'change' }
        ]
      },
      defaultVal: '',
      treeList: [],
      treeListTotal: 0,
      mapTypeCodeObj: {},
      relativeList: [],
      currentRule: {},
      mapTypeRule: {
        0: '课程',
        1: '课件',
        2: '视频'
      },
      treeDetail: {} //当前技能树详情
    };
  },
  computed: {
    videoExp () { // 理论课件
      return this.$store.getters.getMenuName('videoExp') !== '未知类型';
    },
    coursewareExp () { // 文本课件
      return this.$store.getters.getMenuName('coursewareExp') !== '未知类型';
    },
    experiment () { // 实操课件
      return this.$store.getters.getMenuName('experiment') !== '未知类型';
    },
    course () { // 课程
      return this.$store.getters.getMenuName('course') !== '未知类型';
    },
    exam () { // 考试
      return this.$store.getters.getMenuName('exam') !== '未知类型';
    },
    videoLearn () { // 自学视频
      return this.$store.getters.getMenuName('videoLearn') !== '未知类型';
    },
    // 是否有课件的菜单
    showAllExperiment(){
      return this.videoExp || this.coursewareExp || this.experiment;
    }
  },
  async mounted() {
    //获取字典下的所有方向
    await this.queryWeightList();
    this.getSkillLearn();
    //获取路由参数
    this.routeParams = { ...this.$route.query };
    this.$store.commit('addBreadItem', { name: this.routeParams.name });
    this.getTreeList();
    //   this.queryDetail(this.routeParams.id,'init');
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/skillTreeManage') {
      to.query.inPage = this.$route.query.inPage;
      next();
    } else {
      //跳转至非方案管理页面，清空存储的查询条件
      sessionStorage.removeItem('queryObj');
      next();
    }
  },
  methods: {
    getSkillLearn() {
      getSysConfig({ name: 'skillTreeLearningSequenceControl' }).then((res) => {
        if (res.code == 1) {
          this.skillLearn = res.attribute.data.value == 1 ? true : false;
        }
      });
    },
    setExtensionInput(rule) {
      const index = this.ruleList.findIndex((i) => i.type == rule.type);
      this.formValidate.extension = JSON.stringify({ extension: this.ruleList });
      this.$refs.formValidate.validateField('extension');
    },
    //获取技能树数据,渲染列表
    queryDetail(id, type) {
      return new Promise((resolve, reject) => {
        querySkillChapter(id)
          .then((res) => {
            if (res.code == 1) {
              let datasource = res.data.items;
              const datas = datasource;
              if (type == 'init') {
                this.treeData = datas;
                this.hasRoot = datas ? true : false; //是否已经有根节点
              } else if (type === 'pre') {
                this.preTreeData = datas;
              } else {
                this.treeData = datas;
              }
              resolve(datasource);
            } else {
              this.$Message.error(res.message);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    mapDifficulty(d) {
      const mapd = {
        high: '高级',
        middle: '中级',
        low: '初级'
      };
      return mapd[d];
    },
    mapTypeCode(code) {
      return this.mapTypeCodeObj[code];
    },
    mapType(t) {
      const mapt = {
        1: '岗位',
        2: '技能'
      };
      return mapt[t];
    },
    // 返回方案管理
    returnParent() {
      this.$router.push({
        name: 'skillTreeManage',
        query: {
          inPage: this.$route.query.inPage
        }
      });
    },
    //获取所有能力列表
    showAddRoot() {
      let aa = this.isSelfOprate();
      if (aa) {
        return;
      }
      this.isRoot = true;
      this.editState = false;
      this.oprateModal = true;
      this.formInitFn();
      this.svgData.data = {};
      this.formValidate.isLeafNode = 0;
      //获取所有的技能树
      // this.getTreeList();
    },
    closeModal() {
      this.isRoot = false;
      this.oprateModal = false;
      this.formInitFn();
      this.$refs.formValidate.resetFields();
    },
    // Tree修改按钮
    editTree(event, svgData) {
      //获取所有的技能树
      let aa = this.isSelfOprate();
      if (aa || !svgData.data.isLeafNode) {
        //根节点不需要修改
        return;
      }
      this.editGroup = false;
      this.addType = 0;
      // this.getTreeList();
      this.oprateModal = true;
      const data = svgData && svgData.data;
      // event.stopPropagation()
      this.editState = true;
      this.currentData = JSON.parse(JSON.stringify(data));
      const direction = this.findDirection(data.typeCode);
      if(direction) { //以前的数据这样处理
        data.typeCode = direction;
      }
      // this.setDictTypeCode(direction);
      // 存成default了,兼容一下  去掉type :4 场景
      let extension = data.extension && JSON.parse(data.extension).filter((item) => item.type != 4);
      extension &&
        extension.forEach((item) => {
          console.log(item,'======')
          if (item.content === 'default') {
            item.content = '默认';
          }
          if(item.type== 0){
            item.show = this.course
          }else if(item.type== 1){
             item.show = this.showAllExperiment
          }else if(item.type== 2){
             item.show = this.videoLearn
          }else if(item.type== 3){
            item.show = this.exam
          }
        });
      this.ruleList = data.extension
        ? [...extension]
        : JSON.parse(JSON.stringify(this.ruleListCopy));
        console.log('----',this.ruleList)
      this.formValidate = { ...data,typeCode:data.typeCode ? data.typeCode.split(',') : [] }; //direction: direction
      this.formValidate.extension = JSON.stringify({ extension: this.ruleList });
    },
    findDirection(typecode) {
      const dict = this.dictList.filter((item) => item.dictid == typecode)[0];
      if (dict) {
        return dict.parentid;
      } else {
        return '';
      }
    },
    appendFn(data) {
      this.editState = false;
      this.currentData = JSON.parse(JSON.stringify(data));
      this.currentDataChildren = this.currentData.children
        ? this.currentData.children.map((m) => m.abilityId)
        : [];
      this.level = this.currentData.dirLevel + 1;
      this.currentLevel = data.dirLevel + 1;
      this.preCurrentTotal = this.getCurrentLevelTotal();
      console.log('ttt', this.currentData);
      this.weightAddOrUpdate = false;
      this.abilityAddOrUpdate = true;
    },
    //判断是否为本人
    isSelfOprate(showMessage = true) {
      if (!this.isRootDesigner && this.treeDetail.creator != this.USER_ID) {
        if (showMessage) {
          this.$Message.info('仅当前登录用户或单位管理员能进行创建、修改、删除或绑定等操作');
        }
        return true;
      } else {
        return false;
      }
      // else if (this.treeDetail.collect) {
      //   if (showMessage) {
      //     this.$Message.info('当前技能树已被收藏，无法变更');
      //   }
      //   return true;
      // } else if (this.treeDetail.available) {
      //   if (showMessage) {
      //     this.$Message.info('当前技能树已开启，无法变更');
      //   }
      //   return true;
      // } 
    },
    // 添加按钮
    append(event, data, addType, dropX, dropY) {
      // event.stopPropagation();
      let aa = this.isSelfOprate();
      if (aa) {
        return;
      }
      this.activeId = data;
      this.dropX = dropX;
      this.dropY = dropY;
      this.addType = addType;
      this.editGroup = false;
      this.oprateModal = true;
      this.$refs.formValidate.resetFields();
      this.ruleList = JSON.parse(JSON.stringify(this.ruleListCopy));
      //获取所有的技能树
      // this.getTreeList();
      this.creatParentBtn('formValidate');
    },
    delItem(svgData) {
      return new Promise((resolve, reject) => {
        let aa = this.isSelfOprate();
        if (aa) {
          return;
        }
        const data = svgData.data;
        delSkillChapter(data.id).then((res) => {
          if (res.code == 1) {
            // this.$Message.info('删除数据成功');
            // this.queryDetail(this.routeParams.id);
            // this.oprateModal = false;
            if (!data.parentId) {
              this.hasRoot = false;
            }
            resolve(1);
          } else {
            this.$Message.error(res.message);
            reject();
          }
        });
      });
    },
    formInitFn() {
      // this.addType = 0;
      this.formValidate = {
        name: '',
        difficulty: 'low',
        typeCode: [],
        direction: '',
        isLeafNode: 0,
        type: '1',
        extension: JSON.stringify({ extension: this.ruleList }),
        image: ''
      };
      this.$refs.formValidate.resetFields();
    },
    // 创建按钮
    creatParentBtn() {
      this.abilityAddOrUpdate = false;
      this.weightAddOrUpdate = true;
      this.editState = false;
      this.formInitFn();
    },
    dSubmitBtn: debounce(function() {
      this.submitBtn();
    }, 1000),
    submitBtn() {
      if (this.addType == 1) {
        //从模板中添加
        let { copyTree, links, nodes } = this.currentCopy;
        if (!nodes) {
          this.$Message.info('您尚未复制节点，请先复制!');
          this.setLoad();
          return false;
        }
        console.log(copyTree, this.dropX, this.dropY);
        //当前复制节点的第一个节点
        let rootX = Number(copyTree.x);
        let rootY = Number(copyTree.y);
        //与dropX的差值
        let dx = this.dropX - rootX;
        let dy = this.dropY - rootY;
        //替换一下x,y
        (function dealPos(node) {
          console.log(node.x, node.y);
          node.x = (Number(node.x) + dx).toFixed(2);
          node.y = (Number(node.y) + dy).toFixed(2);
          node.isLeafNode = 1;
          if (node.children && node.children.length > 0) {
            node.children.forEach((cnode) => {
              dealPos(cnode);
            });
          }
        })(copyTree);
        console.log('修改了x,y的copy树', copyTree);
        const passObj = { ...copyTree, links };
        const parentId = this.svgData.data.id;
        const skillId = this.routeParams.id;
        const params = {
          dstCareerSkillId: skillId,
          dstParentId: parentId
        };
        if (!params.dstParentId) delete params.dstParentId;
        nodeCopy(params, passObj).then((res) => {
          if (res.code == 1) {
            this.$Message.info('复制技能节点成功');
            //编辑器画节点和线
            this.$refs.canvasEditor.createCopyNodesAndLinks({
              copyTree: copyTree,
              nodes: this.currentCopy.nodes,
              links: this.currentCopy.links
            });
            this.oprateModal = false;
            //this.queryDetail(this.routeParams.id);
            this.isRoot = false;
            this.hasRoot = true;
          } else {
            this.$Message.error(res.message);
            this.setLoad();
          }
        });
      } else {
        //直接添加
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            let apiInterFace;
            let txt = '添加';
            let {
              name,
              difficulty,
              dirLevel,
              label,
              isLeafNode,
              type,
              typeCode,
              direction,
              extension,
              id,
              parentId,
              image
            } = this.formValidate;
            //extension处理---extension原始值
            let originExtension = [
              { type: 0, content: 'default' ,show:this.course},
              { type: 1, content: 'default' ,show:this.showAllExperiment},
              { type: 2, content: 'default' ,show:this.videoLearn},
              { type: 3, content: 60 ,show:this.exam},
              // { type: 4, content: 50 }
            ];
            originExtension.forEach((item) => {
              if (extension) {
                const e = JSON.parse(extension);
                const i = e.extension.filter((f) => f.type == item.type)[0];
                if (i) {
                  item.content = i.content;
                }
              }
            });
            const extensionStr = JSON.stringify(originExtension);
            let passObj = {
              careerSkillId: this.routeParams.id, //技能树id
              difficulty: difficulty,
              dirLevel: dirLevel,
              extension: extensionStr,
              isLeafNode: isLeafNode,
              label: label,
              name: name,
              parentId: this.svgData.data.id,
              type: type,
              typeCode: typeCode.join(','),
              image
              //"typeId": "string"
            };

            if (this.editState) {
              passObj.id = id;
              passObj.parentId = parentId;
              apiInterFace = modifySkillChapter;
              txt = '修改';
            } else {
              apiInterFace = addSkillChapter;
              if (this.isRoot) {
                //如果是根节点
                delete passObj.parentId;
                passObj.dirLevel = 1;
                passObj.label = 1;
              } else {
                let label = this.svgData.data.children.length + 1;
                passObj.dirLevel = this.svgData.data.dirLevel + 1;
                passObj.label = label;
              }
              txt = '创建';
            }
            if (!isLeafNode) {
              //如果不是叶子节点，删除extension字段
              delete passObj.extension;
              delete passObj.typeCode;
              // delete passObj.difficulty;
            }
            // this.setLoad();

            console.log(passObj);
            apiInterFace(passObj).then((res) => {
              if (res.code == 1) {
                this.$Message.info(txt + '技能树节点成功');
                this.oprateModal = false;
                if (this.isRoot) {
                  this.isRoot = false;
                  this.hasRoot = true;
                }
                if (txt == '修改') {
                  //更新canvas节点
                  console.log(this.$refs.canvasEditor);
                  this.$refs.canvasEditor.updateNode(passObj);
                }
                //this.queryDetail(this.routeParams.id);
              } else {
                this.$Message.error(res.message);
              }
              this.setLoad();
            });
          } else {
            this.$Message.error('表单输入有误,请按提示输入');
            this.setLoad();
          }
        });
      }
    },
    setLoad() {
      this.load = false;
      this.$nextTick(() => {
        this.load = true;
      });
    },
    setDictTypeCode(id) {
      this.dictListTypeCode = this.dictList.filter((item) => item.parentid == id);
    },
    //获取权重列表
    async queryWeightList() {
      const { code, attribute, message } = await experType('newDirectionType');
      if (code == 1) {
        this.dictList = attribute.attribute[0].dictEntryList;
        this.dictListDirection = this.dictList.filter((item) => !item.parentid);
        this.dictListTypeCode = this.setDictTypeCode(this.dictListDirection[0].dictid);
        this.dictList.forEach((item) => {
          this.mapTypeCodeObj[item.dictid] = item.dictname;
        });
      } else {
        this.$Message.error(message);
      }
    },
    //外部js调用的函数
    handlerDataUpdate(data, eType) {
      //eType 事件类型
      // this.editGroup = eType === 'mouseenter' ? true : false;
      // if(this.editGroup == false){
      //     return
      // }
      this.svgData = data || { data: {} }; //当前节点的数据
    },
    hideOperate() {
      if (this.editGroup) {
        this.editGroup = false;
      }
    },
    showOprate() {
      this.editGroup = true;
    },
    alertMsg() {
      this.$Message.info('根节点不能复制叶子节点');
    },
    setSmallTreePre(id, name) {
      if (id) {
        this.activeId = id;
        this.activeName = name;
        //   this.queryDetail(id,'pre');
        //   this.queryDetail(id,{width:400,height:300,id:'preTree',
        //   cb:this.addDataFromTree,'font-size':'16px',isRoot:this.isRoot,
        //   alertMsg:this.alertMsg
        //   })
      } else {
        //   this.initTree(null,{id:'preTree'})
      }
    },
    searchTree() {
      this.queryObj.pageIndex = 1;
      // this.getTreeList();
    },
    // 获取当前技能树详情
    getTreeList() {
      let params = { ...this.queryObj };
      if (!this.queryObj.name) {
        delete params.name;
      }
      querySkill(params).then((data) => {
        if (data.code === 1) {
          this.treeDetail = data.data.items[0];
          // this.treeList = data.data.items;
          // this.treeListTotal = data.data.total;
          // const defaultVal = this.treeList[0];
          // if (defaultVal) {
          //     this.setSmallTreePre(defaultVal.id, defaultVal.name);
          // } else {
          //     this.setSmallTreePre(null, null);
          // }
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    pageChange(page) {
      this.queryObj.pageIndex = page;
      this.getTreeList();
    },
    sizeChange(size) {
      this.queryObj.pageSize = size;
      this.getTreeList();
    },
    changeAddType(val) {
      this.queryObj.name = '';
      if (val == 1) {
        this.$nextTick(() => {
          let defaultVal = this.treeList[0];
          if (defaultVal) {
            this.setSmallTreePre(defaultVal.id, defaultVal.name);
          } else {
            this.setSmallTreePre(null, null);
          }
        });
      }
    },
    addDataFromTree(data) {
      //console.log(data);
      this.currentCopy = data || {};
      //this.$Message.info('节点复制成功')
    },
    // addDataFromTree(data){
    //   //console.log(data);
    //   this.currentCopy = data ||{};
    //   //this.$Message.info('节点复制成功')
    // },
    //禁用右键
    handlePaste(e) {
      e.preventDefault();
      return false;
    },
    //创建叶子节点关系
    appendRelative(e, data) {
      //  e.stopPropagation();
      let aa = this.isSelfOprate(false);
      this.editGroup = false;
      this.$refs.skillTreePlan.openModel(data.data, aa);
    },
    updatePoints() {
      this.leaftDetail(this.svgData.data.id).then((points) => {
        this.$refs.canvasEditor.updateNode(points, 'points');
      });
    },
    //展示叶子节点信息
    leaftDetail(id) {
      return new Promise((resolve, reject) => {
        let params = {
          pageIndex: 1,
          pageSize: 9999,
          chapterId: id
        };
        querySkillPoint(params).then((res) => {
          if (res.code == 1) {
            this.relativeList = res.data.items;
            resolve(this.relativeList);
          } else {
            this.$Message.error(res.message);
          }
        });
      });
    },
    clearData() {
      this.relativeList = [];
    },
    showLeaftDetail(e, data) {
      this.editGroup = false;
      this.$refs.skillTreePlan.openModel(data.data, 'detail');
    },
    getUrl(file) {
      this.formValidate.image = file.filePath;
    },
    handleImage(logo) {
      let src = '';
      if (logo) {
        if (logo.indexOf('Learn') > -1) {
          src = logo;
        } else {
          src = `/Learn/${logo}`;
        }
      }
      // else {
      // 	src = this.defaultImg
      // }
      return src;
    }
  }
};
</script>
<style scoped src="./skill.css"></style>
<style scoped>
.chose-wrap {
  display: flex;
  justify-content: space-between;
  padding: 3px 8px;
  background-color: var(--table-tr-hover-color);
  align-items: center;
  margin-top: 10px;
}

.chose-name {
  width: 300px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.tip {
  color: #f90;
  margin-right: 16px;
  line-height: 35px;
}
.operateDiv {
  position: absolute;
  z-index: 99999;
  padding: 2px 8px;
  font-size: 20px;
  background: #fff;
}
.contentWrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden auto;
  background: url('../../../assets/tree2/bg.jpg') white;
  padding:16px;
}
.treeWrap {
  flex: 1;
}
</style>
